package com.fc.happyteam.config;

import com.fc.happyteam.common.upload.DefaultFileUploadManager;
import com.fc.happyteam.common.upload.FileUploadManager;
import com.fc.happyteam.common.upload.QiniuFileUploadManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.MultipartConfigElement;

@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(QiniuProps.class)
public class FileUploadConfiguration {

    @Autowired
    private QiniuProps qiniuProps;

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息，
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize("10MB"); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("10MB");
        // Sets the directory location where files will be stored.
        // factory.setLocation("路径地址");
        return factory.createMultipartConfig();
    }

    @Bean
    public FileUploadManager qiniuUploadManager() {
        FileUploadManager fileUploadManager = new QiniuFileUploadManager(
                qiniuProps.getAccessKey(),
                qiniuProps.getSecretKey(),
                qiniuProps.getBucket(),
                qiniuProps.getImgHost()
        );
        return fileUploadManager;
    }

    @Bean
    @ConditionalOnMissingBean
    public FileUploadManager defaultUploadManager() {
        DefaultFileUploadManager fileUploadManager = new DefaultFileUploadManager();
        return fileUploadManager;
    }
}
